package cn.stylefeng.guns.modular.hx.storage.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.hx.storage.entity.HxCollectingCenter;
import cn.stylefeng.guns.modular.hx.storage.entity.HxCollectionLocation;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageOut;
import cn.stylefeng.guns.modular.hx.storage.mapper.HxCollectingCenterMapper;
import cn.stylefeng.guns.modular.hx.storage.mapper.HxCollectionLocationMapper;
import cn.stylefeng.guns.modular.hx.storage.mapper.HxStorageOutMapper;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxCollectingCenterParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxCollectionLocationParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageOutParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxCollectingCenterResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxCollectionLocationResult;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageOutResult;
import  cn.stylefeng.guns.modular.hx.storage.service.HxCollectingCenterService;
import cn.stylefeng.guns.modular.hx.storage.service.HxCollectionLocationService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOutService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lww
 * @since 2024-01-02
 */
@Service
public class HxCollectingCenterServiceImpl extends ServiceImpl<HxCollectingCenterMapper, HxCollectingCenter> implements HxCollectingCenterService {


    @Resource
    private HxCollectionLocationMapper hxCollectionLocationMapper;

    @Autowired
    private UserService userService;

    @Resource
    private HxStorageOutMapper hxStorageOutMapper;

    @Autowired
    private HxStorageOutService hxStorageOutService;

    @Autowired
    private HxCollectionLocationService hxCollectionLocationService;

    @Override
    public void add(HxCollectingCenterParam param){
        HxCollectingCenter entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(HxCollectingCenterParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(HxCollectingCenterParam param){
        HxCollectingCenter oldEntity = getOldEntity(param);
        HxCollectingCenter newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void zhuanyi(HxCollectingCenterParam param) {
        //通过通道号获取要转移通道的状态
        HxCollectionLocationParam q = new HxCollectionLocationParam();
        q.setDeptId(param.getDeptId());
        q.setOperateId(param.getOperateId());
        q.setLocation(param.getOldLocation());
        q.setStockPort(param.getOldStockPort());
        HxCollectionLocationResult byLocationResult1 = hxCollectionLocationMapper.findByLocationResult(q);
        q = new HxCollectionLocationParam();
        q.setDeptId(param.getDeptId());
        q.setOperateId(param.getOperateId());
        q.setLocation(param.getLocation());
        q.setStockPort(param.getStockPort());
        HxCollectionLocationResult byLocationResult2 = hxCollectionLocationMapper.findByLocationResult(q);
        HxCollectionLocation update = null;
        if(byLocationResult1 != null && byLocationResult2 != null){
            update = new HxCollectionLocation();
            update.setId(byLocationResult1.getId());
            update.setGetUnit("");
            update.setGetUnitId("");
            update.setStatus("");
            update.setTrayNumber("");
            update.setTrayId(null);
            hxCollectionLocationMapper.updateById(update);

            update = new HxCollectionLocation();
            update.setId(byLocationResult2.getId());
            update.setGetUnit(byLocationResult1.getGetUnit());
            update.setGetUnitId(byLocationResult1.getGetUnitId());
            update.setStatus(byLocationResult1.getStatus());
            update.setTrayNumber(byLocationResult1.getTrayNumber());
            update.setTrayId(byLocationResult1.getTrayId());
            hxCollectionLocationMapper.updateById(update);
            HxStorageOutParam hxStorageOutParam = new HxStorageOutParam();
            hxStorageOutParam.setStartState("未发车");
            hxStorageOutParam.setPrintNumb("未打印");
            hxStorageOutParam.setStockPort(param.getOldStockPort());
            hxStorageOutParam.setDeptId(param.getDeptId());
            hxStorageOutParam.setOperateId(param.getOperateId());
            List<HxStorageOutResult> hxStorageOutResults = hxStorageOutMapper.customList(hxStorageOutParam);
            if(hxStorageOutResults != null && hxStorageOutResults.size() > 0){
                HxStorageOutParam updateObj = null;
                for(HxStorageOutResult obj : hxStorageOutResults){
                    updateObj = new HxStorageOutParam();
                    updateObj.setStockPort(param.getStockPort());
                    updateObj.setId(obj.getId());
                    hxStorageOutService.update(updateObj);
                }
            }
//            HxStorageOutParam hxStorageOutParam = new HxStorageOutParam();
//            hxStorageOutParam.setOldStockPort(param.getOldStockPort());
//            hxStorageOutParam.setOldTrayNumber(byLocationResult1.getTrayNumber());
//            hxStorageOutParam.setStockPort(param.getStockPort());
//            hxStorageOutParam.setTrayNumber(byLocationResult1.getTrayNumber());
//            hxStorageOutMapper.updateByStokPort(hxStorageOutParam);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void zhuanyi2(HxCollectingCenterParam param) {
        //通过通道号获取要转移通道的状态
        HxCollectionLocationParam q = new HxCollectionLocationParam();
        q.setDeptId(param.getDeptId());
        q.setOperateId(param.getOperateId());
        q.setStockPort(param.getStockPort());
        q.setOldStockPort(param.getOldStockPort());
        hxCollectionLocationMapper.updateByStockPort(q);
        hxCollectionLocationMapper.updateByStockPortNull(q);

        HxStorageOutParam hxStorageOutParam = new HxStorageOutParam();
        hxStorageOutParam.setStartState("未发车");
        hxStorageOutParam.setPrintNumb("未打印");
        hxStorageOutParam.setStockPort(param.getOldStockPort());
        hxStorageOutParam.setDeptId(param.getDeptId());
        hxStorageOutParam.setOperateId(param.getOperateId());
        List<HxStorageOutResult> hxStorageOutResults = hxStorageOutMapper.customList(hxStorageOutParam);
        if(hxStorageOutResults != null && hxStorageOutResults.size() > 0){
            HxStorageOutParam updateObj = null;
            for(HxStorageOutResult obj : hxStorageOutResults){
                updateObj = new HxStorageOutParam();
                updateObj.setStockPort(param.getStockPort());
                updateObj.setId(obj.getId());
                hxStorageOutService.update(updateObj);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData zhuidan(String stockPort) {
        User user = userService.getcurrentUser();
        String stp = stockPort.split("-")[1];
        //判断巷道内未使用托位
        HxCollectionLocationParam q = new HxCollectionLocationParam();
        if(user.getDeptId() != null){
            q.setDeptId(user.getDeptId());
        }

        if(user.getOperateId() != null){
            q.setOperateId(user.getOperateId());
        }
        q.setStockPort(stp);
        List<HxCollectionLocationResult> hxCollectionLocationResults = this.hxCollectionLocationMapper.customList(q);
        List<HxCollectionLocationResult> LocationLists = new ArrayList<>();
        String getUnitId = "";
        String getUnit = "";
        for(HxCollectionLocationResult obj : hxCollectionLocationResults){
            if(ToolUtil.isEmpty(obj.getGetUnitId())){
                LocationLists.add(obj);
            }else{
                if(ToolUtil.isNotEmpty(getUnitId) && !getUnitId.equals(obj.getGetUnitId())){
                    return ResponseData.error("巷道内已分配多家店，无法追加！！！");
                }
                getUnit = obj.getGetUnit();
                getUnitId = obj.getGetUnitId();
            }
        }
        if(LocationLists.size() < 1){
            return ResponseData.error("巷道已无多余位置，无法追加！！！");
        }
        if(ToolUtil.isEmpty(getUnitId)){
            return ResponseData.error("巷道内未分配门店，无法追加！！！");
        }
        //查询已分配门店，拣货单数，
        LambdaQueryChainWrapper<HxStorageOut> select1 = hxStorageOutService.lambdaQuery()
                .eq(HxStorageOut::getGetUnitId, getUnitId)
                .eq(HxStorageOut::getDeptId, user.getDeptId())
                .eq(HxStorageOut::getStockPort, "")
                .eq(HxStorageOut::getStorageState, "待拣货")
                .select();
        if(select1 == null || select1.list().size() < 1){
            return ResponseData.error("未找到要追加的拣货单，无法追加！！！");
        }
        List<HxStorageOut> lists = new ArrayList<>();
        lists.addAll(select1.list());
        int outCnt = lists.size();
        for(int i=0; i< outCnt ; i++){
            if(i>= LocationLists.size()){
                break;
            }
            hxStorageOutService.lambdaUpdate()
                    .set(HxStorageOut::getStockPort, stp)
                    .eq(HxStorageOut::getId, lists.get(i).getId())
                    .update();
            hxCollectionLocationService.lambdaUpdate()
                    .set(HxCollectionLocation::getStatus, "已分配")
                    .set(HxCollectionLocation::getGetUnitId, getUnitId)
                    .set(HxCollectionLocation::getGetUnit, getUnit)
                    .eq(HxCollectionLocation::getId, LocationLists.get(i).getId())
                    .update();
        }
        return ResponseData.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData chongfen(String stockPort) {
        User user = userService.getcurrentUser();
        String stp = stockPort.split("-")[1];
        //判断巷道内未使用托位
        HxCollectionLocationParam q = new HxCollectionLocationParam();
        if(user.getDeptId() != null){
            q.setDeptId(user.getDeptId());
        }

        if(user.getOperateId() != null){
            q.setOperateId(user.getOperateId());
        }
        q.setStockPort(stp);
        List<HxCollectionLocationResult> hxCollectionLocationResults = this.hxCollectionLocationMapper.customList(q);
        for(HxCollectionLocationResult obj : hxCollectionLocationResults){
            if(ToolUtil.isNotEmpty(obj.getStatus()) && "已占用".equals(obj.getStatus())){
                return ResponseData.error("巷道内存在【已占用】状态，无法重新分配！！！");
            }
        }

        for(HxCollectionLocationResult obj : hxCollectionLocationResults){
            if(ToolUtil.isNotEmpty(obj.getTrayId())){
                hxStorageOutService.lambdaUpdate()
                        .set(HxStorageOut::getStockPort, null)
                        .eq(HxStorageOut::getId, obj.getTrayId())
                        .update();
            }
            hxCollectionLocationService.lambdaUpdate()
                    .set(HxCollectionLocation::getStatus, null)
                    .set(HxCollectionLocation::getGetUnitId, null)
                    .set(HxCollectionLocation::getGetUnit, null)
                    .set(HxCollectionLocation::getTrayId, null)
                    .set(HxCollectionLocation::getTrayNumber, null)
                    .eq(HxCollectionLocation::getId, obj.getId())
                    .update();
        }

        return ResponseData.success();
    }


    @Override
    public HxCollectingCenterResult findBySpec(HxCollectingCenterParam param){
        return null;
    }

    @Override
    public List<HxCollectingCenterResult> findListBySpec(HxCollectingCenterParam param){
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(HxCollectingCenterParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<HxCollectionLocationResult> cha(HxCollectingCenterParam hxCollectingCenterParam) {
        return this.baseMapper.cha(hxCollectingCenterParam);
    }

    @Override
    public void updateBySpec(HxCollectingCenterParam hxCollectingCenterParam) {
        this.baseMapper.updateBySpec(hxCollectingCenterParam);
    }

    @Override
    public void insertStockPort(HxCollectingCenterParam hxCollectingCenterParam) {
        this.baseMapper.insertStockPort(hxCollectingCenterParam);
    }

    @Override
    public void insertCollectionLocation(HxCollectionLocationParam hxCollectionLocationParam) {
        this.baseMapper.insertCollectionLocation(hxCollectionLocationParam);
    }

    @Override
    public Long chaStockPortId(HxCollectingCenterParam hxCollectingCenterParam) {
        return this.baseMapper.chaStockPortId(hxCollectingCenterParam);
    }



    private Serializable getKey(HxCollectingCenterParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private HxCollectingCenter getOldEntity(HxCollectingCenterParam param) {
        return this.getById(getKey(param));
    }

    private HxCollectingCenter getEntity(HxCollectingCenterParam param) {
        HxCollectingCenter entity = new HxCollectingCenter();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
